<template>
	<view class="page-container">
		<view class="greeting-section">
			<view class="report-title-container">
				<text class="greeting-text">{{reportDetail ? reportDetail.title : '加载中...'}}</text>
			</view>
			
			<view class="report-date-header" v-if="reportDetail">
				<image class="calendar-icon" src="/static/images/czbg.png"></image>
				<text class="report-date-text">{{ reportDetail.startDate }} - {{ reportDetail.endDate }}</text>
			</view>
		</view>

		<scroll-view class="reports-scroll-view" scroll-y>
            <view class="report-main-content-area" v-if="reportDetail">
                <view class="report-card"  :style="{ backgroundColor: backgroundColor }">
                    <view class="report-content-wrapper">
						<view class="report-text-content" v-html="reportDetail.summaryContent"></view>

<!--                        <text class="report-text-content">{{reportDetail.summaryContent}}</text -->
                    </view>
                </view>
            </view>
            <view v-else-if="!isLoading && !reportDetail" class="no-reports">
                <text>暂无成长报告</text>
            </view>
            <view v-if="isLoading" class="loading-indicator"> <text>正在加载报告...</text>
            </view>
		</scroll-view>
	</view>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app'; // onShow might be needed if you refresh data on page show
import { getDeviceReport } from '../../app/device'; // ENSURE THIS PATH IS CORRECT

// Define the type for a single report object
interface ReportDetail {
  userId: string;
  deviceId: string;
  startDate: string;
  endDate: string;
  summaryContent: string;
  title: string; // Included as it was in your original data structure
}

// 当前日期
const currentDate = new Date()
// 当前是第几周
const currentWeek = ref(1)
// 背景颜色
const backgroundColor = ref('#ffffff')


// 根据周数设置背景颜色
const setBackgroundByWeek = (week: number) => {
  const colors = [
    '#F5E0B1',  // 第1周 
    '#90DABC',  // 第2周 
    '#F1B3C2',  // 第3周 
    '#C7D9E7',  // 第4周 
    '#B0C7F0'   // 第5周 
  ]
  
  // 确保周数在有效范围内
  const weekIndex = Math.min(week - 1, colors.length - 1)
  backgroundColor.value = colors[weekIndex]
}

// 直接在组件中定义函数
function getWeekOfMonth(date: Date): number {
  const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
  const firstDayOfWeek = firstDay.getDay() || 7; // 转换为周一到周日为1-7
  const dayOfMonth = date.getDate();
  
  return Math.ceil((dayOfMonth + firstDayOfWeek - 1) / 7);
}

// Store the single report object
const reportDetail = ref<ReportDetail | null>(null); // Initialize as null
const isLoading = ref(false); // For loading state

const deviceId = ref<string>('');

onLoad((options) => {
  // uni-app options might be undefined or options.deviceId might be undefined
  const currentOptions = options as { deviceId?: string } | undefined;

  if (currentOptions && currentOptions.deviceId) {
    deviceId.value = currentOptions.deviceId;
    fetchDeviceReportData(deviceId.value);
  } else {
    console.warn('deviceId not provided in onLoad options');
    reportDetail.value = null; // Ensure it's null if no ID
  }
});

onMounted(() => {
  currentWeek.value = getWeekOfMonth(currentDate);
  	setBackgroundByWeek(currentWeek.value)
});

const fetchDeviceReportData = async (id: string) => {
  isLoading.value = true;
  reportDetail.value = null; // Reset before fetching
  try {
    // Ensure getDeviceReport is correctly imported and returns a Promise
    // The structure of 'res' depends on your actual API client
    // Assuming 'res.data' holds the report object based on your previous code
    const res = await getDeviceReport(id);
    console.log('API Response:', res);

    // Check if res and res.data exist, and res.data is an object (not an array)
    if (res && res.data && typeof res.data === 'object' && !Array.isArray(res.data)) {
      reportDetail.value = res.data as ReportDetail;
      console.log('Report Detail:', reportDetail.value);
    } else if (res && Array.isArray(res.data) && res.data.length > 0 && typeof res.data[0] === 'object') {
      // Fallback if API by mistake returns an array with one item
      console.warn('API returned an array with one item, using the first element.');
      reportDetail.value = res.data[0] as ReportDetail;
    }
     else {
      console.warn('No data or unexpected data format received from getDeviceReport. Response data:', res ? res.data : 'undefined');
      reportDetail.value = null;
    }
  } catch (err) {
    console.error('获取设备报告失败 (Failed to fetch device report):', err);
    reportDetail.value = null;
  } finally {
    isLoading.value = false;
  }
};

// Any other methods you might need can be added here
// e.g., handleBack, playSummary etc. if they are still relevant.

</script>

<style>
	page {
		height: 100%;
		background-color: #F8F8F8; /* Light grey background for the whole page */
	}

	.page-container {
		display: flex;
		flex-direction: column;
		height: 100%;
		background-color: #FFFFFF;
	}

	/* Greeting Section and Title/Date styling */
	.greeting-section {
		padding: 30rpx 40rpx 0rpx 40rpx; /* Adjusted bottom padding */
		text-align: left;
		background-color: #FFFFFF; /* Ensure it has a background if needed */
	}

    /* NEW: Container for the title to add bottom margin */
	.report-title-container {
		margin-bottom: 30rpx;
	}

	.greeting-text { /* This is effectively your report title style now */
		color: #000000; /* Darker color for title */
		font-family: Source Han Sans, Source Han Sans;
		font-weight: 350;
		font-size: 30rpx;
	}

	.report-date-header {
		/* background: #FFFFFF; No longer needed if greeting-section has white bg */
		display: flex;
		align-items: center;
		/* margin-bottom: 25rpx; This margin is now handled by report-title-container or padding of greeting-section */
        padding-bottom: 25rpx; /* Add padding to the bottom of the date header instead of margin */
	}

	.calendar-icon {
		width: 40rpx;
		height: 40rpx;
		margin-right: 20rpx;
	}

	.report-date-text {
		font-size: 28rpx;
		color: #007AFF;
		font-weight: 400;
	}

	/* Scroll View for Reports */
	.reports-scroll-view {
		flex: 1;
		height: 0; /* Allows flex to control height */
		width: 100%;
		background-color: #F8F8F8; /* Background for the scrollable area */
	}
    
    /* Container within scroll-view for padding */
    .report-main-content-area {
        padding: 20rpx 20rpx 20rpx 20rpx; 
		background-color: #FFFFFF;
		width: 100%;
    }


	/* Individual Report Card */
	.report-card {
		background-color: #E0EFFF;
		padding: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
		border-radius: 20rpx;
        width: 87%; 
	}
	
	.report-text-content {
		font-family: Source Han Sans, Source Han Sans;
		font-weight: 350;
		font-size: 30rpx;
		line-height: 43rpx;
		color: #FFFFFF;
		text-align: left;
		font-style: normal;
		text-transform: none;
	  white-space: pre-wrap; /* 保留空白、换行，自动换行 */
	  word-wrap: break-word; /* 防止长单词溢出 */
	}

	/* Loading and No Reports States */
	.loading-indicator,
	.no-reports {
		text-align: center;
		padding: 80rpx 40rpx; /* More padding */
		color: #999999;
		font-size: 28rpx;
		background-color: #F8F8F8; /* Match scroll view background */
	}
</style>